package com.accl.poc;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.apache.commons.codec.digest.DigestUtils;

public class HashUtils {

	public static final String SERVLET_CONTEXT_CODE = "SERVLET_CONTEXT_CODE";

	public static final String sha1(String string) {
		return DigestUtils.shaHex(string);
	}

	@SuppressWarnings("unchecked")
	public static final String generate(ServletContext servletContext) {
		Map<String, Long> hashCodeMap = (Map<String, Long>) servletContext
				.getAttribute(SERVLET_CONTEXT_CODE);
		if (hashCodeMap == null) {
			hashCodeMap = new HashMap<String, Long>();
		}
		String code = UUID.randomUUID().toString();
		hashCodeMap.put(code, new Date().getTime());
		servletContext.setAttribute(SERVLET_CONTEXT_CODE, hashCodeMap);
		return code;
	}

	@SuppressWarnings("unchecked")
	public static final boolean valid(String hashCode,
			ServletContext servletContext) {
		boolean valid = false;
		Map<String, Long> hashCodeMap = (Map<String, Long>) servletContext
				.getAttribute(SERVLET_CONTEXT_CODE);
		if (hashCodeMap != null && hashCodeMap.get(hashCode) != null) {
			Long time = hashCodeMap.get(hashCode);
			Date date = new Date();
			// System.out.println(date);
			// System.out.println("time of hashCode = " + time);
			// System.out.println("current time = " + date.getTime());
			// System.out.println(date.getTime() - time);
			if (date.getTime() - time <= 10000) {
				valid = true;
			}
		}
		return valid;
	}
}
